package com.common.frame.base

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Paint
import android.graphics.Typeface
import android.graphics.drawable.Drawable
import android.text.*
import android.text.style.AbsoluteSizeSpan
import android.util.TypedValue
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.BindingAdapter
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.bumptech.glide.load.resource.bitmap.CenterCrop
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.bumptech.glide.request.RequestOptions
import com.bumptech.glide.request.target.CustomTarget
import com.bumptech.glide.request.target.SimpleTarget
import com.bumptech.glide.request.transition.Transition
import com.bumptech.glide.signature.ObjectKey
import com.common.frame.extension.setSingleClick
import com.common.frame.utils.ScreenUtil
import com.common.frame.utils.ScreenUtil.dip2px
import com.common.frame.utils.StatusBarUtil
import com.common.frame.utils.Utils
import com.common.frame.widget.ChineseFilter


@BindingAdapter("hintSize")
fun hintSize(editText: EditText?, size: Int) {
    val hintText = editText?.hint.toString()
    val ss = SpannableString(hintText) //定义hint的值
    val ass = AbsoluteSizeSpan(size, true) //设置字体大小 true表示单位是sp
    ss.setSpan(ass, 0, ss.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
    editText?.hint = SpannedString(ss)
}

@BindingAdapter("lineType")
fun setLineType(textView: TextView, lineType: Int) {
    when (lineType) {
        1 -> textView.paint.flags = Paint.UNDERLINE_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG; //下划线
        2 -> textView.paint.flags =
            Paint.STRIKE_THRU_TEXT_FLAG or Paint.ANTI_ALIAS_FLAG // 设置中划线并加清晰
    }
}

@BindingAdapter("isFakeBoldText")
fun TextView.setFakeBoldText(isFakeBoldText: Boolean) {
    paint.isFakeBoldText = isFakeBoldText
}

@BindingAdapter("htmlText")
fun TextView.setHtmlText(htmlText: String?) {
    text = Html.fromHtml(htmlText ?: "")
}

@BindingAdapter("isSelect")
fun definitionSelect(view: View, resId: Int) {
    view.isSelected = view.id == resId
}

@BindingAdapter("isSelect")
fun isSelect(view: View, isSelect: Boolean) {
    view.isSelected = isSelect
}

@BindingAdapter("visible")
fun visible(view: View, visible: Boolean) {
    view.visibility = if (visible) View.VISIBLE else View.GONE
}

@BindingAdapter("invisible")
fun invisible(view: View, invisible: Boolean) {
    view.visibility = if (invisible) View.VISIBLE else View.INVISIBLE
}

@BindingAdapter("marginTop")
fun View.marginTop(marginTop: Int) {
    val params = layoutParams as ViewGroup.MarginLayoutParams
    params.setMargins(
        params.leftMargin, marginTop,
        params.rightMargin, params.bottomMargin
    )
    layoutParams = params
}

@BindingAdapter("marginBottom")
fun View.marginBottom(marginBottom: Int) {
    val params = layoutParams as ViewGroup.MarginLayoutParams
    params.setMargins(
        params.leftMargin, params.topMargin,
        params.rightMargin, marginBottom
    )
    layoutParams = params
}


@BindingAdapter("viewHeight")
fun viewHeight(view: View, height: Int) {
    val layoutParams = view.layoutParams as ViewGroup.MarginLayoutParams
    layoutParams.height =
        if (height == 0) dip2px(view.context, 0.1f) else dip2px(view.context, height.toFloat())
    view.layoutParams = layoutParams
}

@BindingAdapter("viewWidth")
fun viewWidth(view: View, width: Int) {
    val layoutParams = view.layoutParams as ViewGroup.MarginLayoutParams
    layoutParams.width =
        if (width == 0) dip2px(view.context, 0.1f) else dip2px(view.context, width.toFloat())
    view.layoutParams = layoutParams
}


@BindingAdapter("loadResImg")
fun ImageView.loadResImg(resId: Int) {
    setImageResource(resId)
}


@BindingAdapter("loadCircleImg")
fun ImageView.loadCircleImg(url: String?) {
    Glide.with(context).load(url)
        .apply(RequestOptions.bitmapTransform(CircleCrop()))
        .into(this)
}

@BindingAdapter("loadCircleImg", "placeholder", requireAll = false)
fun ImageView.loadCircleImage( url: String?, placeholder: Int) {
    Glide.with(context).load(url)
        .apply(RequestOptions.bitmapTransform(CircleCrop()))
        .placeholder(placeholder)
        .error(placeholder)
        .into(this)
}
@BindingAdapter("loadCircleImg", "placeholder", requireAll = false)
fun ImageView.loadCircleImage( url: String?, placeholder: Drawable) {
    Glide.with(context).load(url)
        .apply(RequestOptions.bitmapTransform(CircleCrop()))
        .placeholder(placeholder)
        .error(placeholder)
        .into(this)
}
@BindingAdapter("loadImg")
fun ImageView.loadImg(url: String?) {
    Glide.with(context)
        .load(url).placeholder(drawable)
        .into(this)
}

@BindingAdapter("loadRoundImg", "radius")
fun ImageView.loadRoundImg(url: String?, radius: Int) {
    Glide.with(context)
        .load(url)
        .apply(RequestOptions().transforms(CenterCrop(), RoundedCorners(radius)))
        .into(this)
}

@BindingAdapter("previewImg")
fun loadPreviewImage(imageView: ImageView, pageImgPath: String?) {
    Glide.with(imageView.context).load(pageImgPath)
        .apply(
            RequestOptions().placeholder(imageView.drawable)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
        )
        .into(imageView)
}

@BindingAdapter("noCacheImg", "signKey")
fun ImageView.loadImageNoCache( url: String?, signKey: String) {
    Glide.with(context).load(url)
        .signature(ObjectKey(signKey))
        .into(this)
}

@BindingAdapter("loadImg", "placeholder")
fun ImageView.loadImage( url: String?, placeholder: Int) {
    Glide.with(context)
        .load(url).placeholder(placeholder)
        .into(this)
}

fun getBitmap(context: Context, url: String, width: Int, height: Int): Bitmap {
    return Glide.with(context)
        .asBitmap().load(url).submit(width, height).get()
}

fun getImageWidthHeight(
    imageView: ImageView,
    url: String?,
    maxWidth: Int,
    listener: (Float, Float) -> Unit
) {
    Glide.with(imageView.context).asBitmap().load(url)
        .into(object : SimpleTarget<Bitmap?>() {
            override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap?>?) {
                val para = imageView.layoutParams
                var height = ScreenUtil.getScreenHeight(imageView.context)
                var width = height * bitmap.width / bitmap.height
                if (width > maxWidth) {
                    width = maxWidth
                    height = maxWidth * bitmap.height / bitmap.width
                }
                para.width = width
                para.height = height
                imageView.layoutParams = para
                listener(para.width.toFloat(), para.height.toFloat())
                loadPreviewImage(imageView, url)
            }

        })
}

fun setImageWidthHeight(
    imageView: ImageView,
    url: String?,
    maxWidth: Int,
    listener: (Float, Float) -> Unit
) {
    Glide.with(imageView.context).asBitmap().load(url)
        .into(object : SimpleTarget<Bitmap?>() {
            override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap?>?) {
                val para = imageView.layoutParams
                var height = ScreenUtil.getScreenHeight(imageView.context)
                var width = height * bitmap.width / bitmap.height
                if (width > maxWidth) {
                    width = maxWidth
                    height = maxWidth * bitmap.height / bitmap.width
                }
                para.width = width
                para.height = height
                imageView.layoutParams = para
                listener(bitmap.width.toFloat() / para.width, bitmap.height.toFloat() / para.height)
                loadPreviewImage(imageView, url)
            }

        })
}

fun getImageWidthHeight(context: Context, url: String?, listener: (Bitmap) -> Unit) {
    Glide.with(context).asBitmap().load(url)
        .into(object : SimpleTarget<Bitmap?>() {
            override fun onResourceReady(bitmap: Bitmap, transition: Transition<in Bitmap?>?) {
                listener(bitmap)
            }
        })
}


/**
 * 防暴击--间隔1秒生效一次
 */
@BindingAdapter("singleClick")
fun View.onSingleClick( onListener: View.OnClickListener) {
    setSingleClick {
        onListener.onClick(it)
    }
}

/**
 * 固定宽度的情况下，自适应文本字体大小
 */
@BindingAdapter("adjustTextSize", "maxTextWidth", requireAll = false)
fun TextView.adjustTextSize(text: String?, maxTextWidth: Int? = null) {
    setText(text)
    post {
        val realWidth = (maxTextWidth ?: width) - paddingLeft - paddingRight
        if (realWidth <= 0 || TextUtils.isEmpty(text)) {
            return@post
        }
        val textPaintClone = TextPaint(paint)
        var trySize = textPaintClone.textSize
        while (textPaintClone.measureText(text) > realWidth) {
            trySize--
            textPaintClone.textSize = trySize
        }
        setTextSize(TypedValue.COMPLEX_UNIT_PX, trySize)
    }

}

/**
 * url转drawable
 */
@BindingAdapter("loadBgDrawable")
fun View.loadBgDrawable(url: String?) {
    if (!checkContext(context)) {
        return
    }
    Glide.with(context).load(url)
        .into(object : CustomTarget<Drawable?>() {
            override fun onResourceReady(resource: Drawable, t: Transition<in Drawable?>?) {
                background = resource
            }

            override fun onLoadCleared(placeholder: Drawable?) {

            }
        })
}

/**
 * 预加载图片
 */
fun preLoadImg(url: String?) {
    Glide.with(Utils.app).load(url).preload()
}

/**
 * 是否动态设置为状态栏高度的PaddingTop
 */
@BindingAdapter("fitsSystemWindow")
fun View.fitsSystemWindows(fitsSystemWindow: Boolean) {
    if (fitsSystemWindow) {
        setPadding(
            paddingLeft,
            StatusBarUtil.getStatusBarHeight(context) + paddingTop,
            paddingRight,
            paddingBottom
        )
    }
}
/**
 * 限制中文输入
 */
@BindingAdapter("setChineseFilter")
fun setChineseFilter(textView: TextView, isFilter: Boolean) {
    val list = textView.filters.toMutableList()
    if (list.isNotEmpty()) {
        list.add(ChineseFilter())
        textView.filters = list.toTypedArray()
    } else {
        textView.filters = arrayOf(ChineseFilter())
    }
}

/**
 * 校验context
 */
fun checkContext(mContext: Context?): Boolean {
    if (mContext == null) return false
    if (mContext is Activity) {
        if (mContext.isDestroyed) {
            return false
        }
    }
    return true
}

fun View.isInvisibleOrGone(invisible: Boolean) {
    visibility = if (invisible) View.INVISIBLE else View.GONE
}

@BindingAdapter("setDinAlternateBold")
fun TextView.setDinATextView(isDinAlternateBold: Boolean) {
    if (isDinAlternateBold) {
        val tf: Typeface = Typeface.createFromAsset(
            context.assets,
            "fonts/DIN_Alternate_Bold.ttf"
        )
        typeface = tf
    }
}

/**
 *  阿里巴巴普惠粗体
 */
@BindingAdapter("setAliSansBoldText")
fun TextView.setAliSansBoldText(setAliSansBlackText: Boolean) {
    if (setAliSansBlackText) {
        val tf: Typeface = Typeface.createFromAsset(
            context.assets,
            "fonts/AlibabaSans-Bold.otf"
        )
       typeface = tf
    }
}

/**
 *  优设标题黑字体
 *  YouSheBiaoTiHei
 */
@BindingAdapter("setYouSheHeiText")
fun TextView.setYouSheHeiText( setYouSheHei: Boolean) {
    if (setYouSheHei) {
        val tf: Typeface = Typeface.createFromAsset(
            context.assets,
            "fonts/YouSheBiaoTiHei.ttf"
        )
        typeface = tf
    }
}